<template>
  <div class="suggest">
    <scroll ref="suggestScroll" :data="result" :pullup="pullup" :before-scroll="beforeScroll" class="suggestScroll" @scrollToEnd="scrollToEnd" @beforeScroll="listScroll" >
      <ul class="suggest-list">
        <li v-for="(item, index) in result" :key="index" :data-index="index" class="suggest-item" @click="selectItem(item)" >
          <div class="icon">
            <i :class="getIconCls(item)" />
          </div>
          <div class="name">
            <p class="text" v-html="getDisplayName(item)" />
          </div>
        </li>
        <loading v-show="hasMore" />
      </ul>
      <div v-show="!result.length && !hasMore" class="no-result-wrapper">
        <no-result title="抱歉，暂无搜索结果" />
      </div>
    </scroll>
  </div>
</template>

<script type="text/ecmascript-6">
import Scroll from 'base/scroll/scroll'
import { search } from 'api/search'
import { ERR_OK } from 'api/config'
// import { getSongVkey } from 'api/song'
// eslint-disable-next-line
import { createSong, isValidMusic, processSongsUrl } from "common/js/song";
import Loading from 'base/loading/loading'
import NoResult from 'base/no-result/no-result'
import Singer from 'common/js/singer'
import { mapMutations, mapActions } from 'vuex'

const TYPE_SINGER = 'singer' // 判断歌手旗帜
const PERPAGE = 20 // 默认20条数据
export default {
  props: {
    query: {
      type: String,
      default: ''
    },
    showSinger: {
      // 是否需要歌手有外界控制
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      page: 1, // 默认第一页
      result: [], // 歌手数组
      Lresult: [], // 歌曲数组
      pullup: true, // 需要上拉刷新
      hasMore: true, // 加载更多旗帜
      beforeScroll: true // 滚动开始触发
    }
  },
  mounted () {
    // setTimeout(() => {
    //   console.log(this.result)
    //   console.log(this.Lresult)
    // }, 5000)
  },
  methods: {
    _search () {
      this.result = []
      this.Lresult = []
      this.page = 1
      this.hasMore = true
      this.$refs.suggestScroll.scrollTo(0, 0, 0)
      search(this.query, this.page, this.showSinger, PERPAGE)
        .then(result => {
          // console.log(Object.is(result.code, ERR_OK))
          // const num1 = result.indexOf('(')
          // const num2 = result.lastIndexOf(')')
          // result = JSON.parse(result.substring(num1 + 1, num2))
          if (result.code === ERR_OK) {
            // 处理数组
            this._genResult(result.data)
            // 判断是否可以加载更多
            this._checkMore(result.data)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    _genResult (data) {
      // 因为歌手加载下一页也有  我们就在第一页的时候 加载进去  其他不加载
      if (
        data &&
        data.zhida &&
        data.zhida.albumid &&
        data.zhida.albummid &&
        this.page === 1
      ) {
        this.result.push({ ...data.zhida, ...{ type: TYPE_SINGER } })
      }

      if (data && data.song && data.song.list) {
        processSongsUrl(this._normalizeSongs(data.song.list)).then(response => {
          this.Lresult = response
        })
      }
    },
    _normalizeSongs (list) {
      const array = []
      list.forEach((item, index) => {
        if (item.songid && item.albummid) {
          if (isValidMusic(item)) {
            array.push(createSong(item))
          }
          // getSongVkey(item.songmid)
          //   .then((result) => {
          //     if (result.code === ERR_OK) {
          //       // console.log(createSong(item, result.data.items[0].vkey))
          //       array.push(createSong(item, result.data.items[0].vkey))
          //     }
          //   })
          //   .catch((error) => {
          //     console.log(error)
          //   })
        }
      })
      return array
    },
    getDisplayName (item) {
      if (item.type === TYPE_SINGER) {
        return item.singername
      } else {
        return item.name + ' - ' + item.singer
      }
    },
    getIconCls (item) {
      if (item.type === TYPE_SINGER) {
        return 'icon-mine'
      } else {
        return 'icon-music'
      }
    },
    // 判断是否加载更多
    _checkMore (data) {
      // console.log(data)
      if (
        !data.song.list.length ||
        data.song.curnum + data.song.curpage * PERPAGE >= data.song.totalnum
      ) {
        this.hasMore = false
      }
    },
    // 加载更多
    scrollToEnd () {
      if (!this.hasMore) {
        return false
      }

      this.page++
      search(this.query, this.page, this.showSinger, PERPAGE)
        .then(result => {
          // console.log(result)
          // const num1 = result.indexOf('(')
          // const num2 = result.lastIndexOf(')')
          // result = JSON.parse(result.substring(num1 + 1, num2))
          // console.log(result)
          if (result.code === ERR_OK) {
            // 处理数组
            this._genResult(result.data)
            // 判断是否可以加载更多
            this._checkMore(result.data)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    selectItem (item) {
      if (item.type === TYPE_SINGER) {
        const singer = new Singer({
          id: item.albumid,
          name: item.singername
        })
        this.setSinger(singer)
        // this.$router.push({name: 'SingerDetailSearch', params: {id: item.albummid}})
      } else {
        this.insertSong(item)
      }

      this.$emit('select', item)
    },
    // 列表滚动就触发
    listScroll () {
      this.$emit('listScroll')
    },
    refresh () {
      this.$refs.suggestScroll.refresh()
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    }),
    ...mapActions(['insertSong'])
  },
  watch: {
    query (newQuery, oladQuery) {
      this._search()
    },
    Lresult (newValue) {
      // 这样子写只会使最后一个被添加进去 其余的不会
      // let newV = newValue[newValue.length - 1]
      // console.log(newValue)
      // if (newV) {
      //   this.result.push(newV)
      // }
      if (newValue.length) {
        newValue.map((item, index) => {
          this.result.push(item)
        })
      }
    }
  },
  components: { Scroll, Loading, NoResult }
}
</script>

<style lang="stylus" scoped rel="stylesheet/stylus">
@import '~common/stylus/variable';

.suggest {
  height: 100%;
  width: 100%;
}

.suggestScroll {
  height: 100%;
  width: 100%;
  overflow: hidden;

  .suggest-list {
    padding: 0 20px;

    .suggest-item {
      display: flex;
      margin-bottom: 20px;
      color: $color-text-d;

      .icon {
        width: 40px;
      }

      .name {
        flex: 1;

        .text {
          display: -webkit-box;
          overflow: hidden;
          white-space: normal !important;
          text-overflow: ellipsis;
          word-wrap: break-word;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
      }
    }
  }

  .no-result-wrapper {
    width: 100%;
    height: 100%;
  }
}
</style>
